package main

import "fmt"

// 相互交换Link的相邻节点
// 思路是先实现任意两个index的交换，然后计算link的len，然后使用i+=2,j+=2 跳着来swap
func main(){

}

type ListNode struct{
	Val int
	Next ListNode
}
func swapPairs(l *ListNode) *ListNode {
	i, j, len := 0, 1, 0

	other := l
	for other != nil {
		len++
		other = other.Next
	}

	for i < j && j < len {
		l = Swap(l, i, j)
		i += 2
		j += 2
	}
	fmt.Println(l)
	return l
}
// swap 是一个很难的操作吧
func Swap(l *ListNode,index1, index2 int) *ListNode {
	if l == nil {
		return l
	}
	other := l
	i := 0
	var node1, node1prev, node2, node2prev *ListNode

	if index1 >= index2 {
		return l
	}

	if index1 == 0 {
		node1 = l
		node1prev = nil
	}

	for other != nil {
		if index1-1 == i {
			node1prev = other
			node1 = node1prev.Next
		}
		if index2-1 == i {
			node2prev = other
			node2 = node2prev.Next
		}

		if node1 != nil && node2 != nil {
			break
		}
		i++
		other = other.Next
	}

	if node1 != nil && node2 != nil {
		if node1prev != nil {
			node1prev.Next = node2
		} else {
			l = node2
		}
		node1next := node1.Next
		node2next := node2.Next

		if node1next != node2 {
			node2.Next = node1next
		}
		if node2prev != node1 {
			node2prev.Next = node1
		} else {
			node2.Next = node1
		}
		node1.Next = node2next
	}
	return l
}